import router from '@/router'
import { CODE_ENUMS } from './enums'
import { useUserStore } from '@/store/modules/user'
import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios'

const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
})

instance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()

        if (userStore.token) {
            config.headers.Authorization = `Bearer ${userStore.token}`
        }

        return config
    },
    (err) => {
        return Promise.reject(err)
    },
)

instance.interceptors.response.use(
    (response: AxiosResponse<API.ResultData>) => {
        const userStore = useUserStore()
        const res = response.data
        switch (res.code) {
            case CODE_ENUMS.SUCCESS: {
                return response
            }
            case CODE_ENUMS.NO_LOGIN: {
                // 登出
                userStore.logoutEffect()
                router.replace('/404')
                break
            }
            case CODE_ENUMS.NO_AUTH: {
                // 跳转
                router.replace('/401')
                break
            }
        }
        return Promise.reject(res.message)
    },
    (err) => {
        return Promise.reject(err)
    },
)

export const http = async <T = any, R = any>(
    config: AxiosRequestConfig,
): Promise<API.ResultData<T, R>> => {
    const response = await instance(config)
    return response.data
}
